﻿namespace Infrastructure.Security.Crc
{
    /// <summary>
    /// ccit验证
    /// </summary>
    public class CCITTHelper
    {
        private int polynomial = 0x1021;

        /// <summary>
        /// 验证
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public int Validate(byte[] bytes)
        {
            int crc = 0xffff;
            for (int index = 0; index < bytes.Length; index++)
            {
                byte b = bytes[index];
                for (int i = 0; i < 8; i++)
                {
                    bool bit = (((b >> (7 - i)) & 1) == 1);
                    bool c15 = (((crc >> 15) & 1) == 1);
                    crc <<= 1;
                    crc &= 0xffff;
                    if (bit)
                        crc += 1;
                    if (c15)
                        crc ^= polynomial;
                }
            }
            crc &= 0xffff;
            for (int i = 0; i < 16; i++)
            {
                bool c15 = (((crc >> 15) & 1) == 1);
                crc <<= 1;
                crc &= 0xffff;
                if (c15)
                    crc ^= polynomial;
            }
            crc &= 0xffff;
            return crc;
        }

    }
}
